<script setup>
import { reactive, ref, onMounted, onUnmounted, nextTick } from 'vue'
import _axios from '../../utils/myAxios.js'
import { ElMessage } from 'element-plus'
import tinymce from 'tinymce'
import { set } from '@vueuse/core';
import { useRouter } from 'vue-router'
const router = useRouter()

async function getAllCategory() {
    let res = await _axios.get('/api/category/allList')
    if (res.data.code == 200) {
        allCategory.value = res.data.data
    } else {
        ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            appendTo: "#app",
        })
    }
}

async function getAllTag() {
    let res = await _axios.get('/api/tag/allList')
    if (res.data.code == 200) {
        allTag.value = res.data.data
    } else {
        ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            appendTo: "#app",
        })
    }
}

//tinymce初始化参数
let init = ref({
    selector: '#tinymce',
    license_key: 'gpl',
    language: 'zh_CN',
    statusbar: false,
    menubar: false,
    toolbar: 'undo redo | styles | bold italic | alignleft aligncenter alignright alignjustify | indent outdent | fontfamily fontsize | copy cut paste | hr | emoticons image link code ',
    plugins: 'emoticons image link code',
    file_picker_types: 'image',
    automatic_uploads: false,
    images_upload_max_size: '2mb',
    image_dimensions: false,
    images_upload_url: 'localhost:8080',
    height: '350',
    setup: function (editor) {
        editor.on('BeforeSetContent', function (e) {
            if (e.content.includes('<img')) {
                e.content = e.content.replace(/<img/g, '<img width="100%" height=""');
            }
        });
    }
})

//文章修改跳过来，查找文章
async function getArticle() {
    const urlParam = new URLSearchParams(window.location.hash.split("?")[1]);
    let id = urlParam.get('articleId')
    if (id != null) {
        let resp = await _axios.get(`/api/article/getArticleById/${id}`)
        if (resp.data.code == 200) {
            article.value = resp.data.data
            if (resp.data.data.categoryId === -1) article.value.categoryId = undefined
            if (resp.data.data.thumbnail === '') fileList.value = []
            else fileList.value.push({
                name: "缩略图", url: resp.data.data.thumbnail
            })
            setTimeout(() => {
                tinymce.activeEditor.setContent(resp.data.data.content)
            }, 500)
        } else {
            ElMessage({
                showClose: true,
                message: resp.data.message,
                type: 'error',
                appendTo: "#app",
            })
        }
    }

}
onMounted(() => {
    getAllCategory()
    getAllTag()

    // tinymce初始化
    tinymce.init(init.value)
    getArticle()
})

onUnmounted(() => {
    // tinymce销毁
    tinymce.remove()
})


let allCategory = ref([
    { id: '', name: '' }
])
let allTag = ref([
    { id: '', name: '', description: '' }
])

let article = ref({ //文章表单数据
    id: undefined,
    title: undefined,
    categoryId: undefined,
    tags: [],
    summary: undefined,
    //是否允许评论 1是，0否
    isComment: 1,
    //是否置顶（0否，1是）
    isTop: 0,
    //状态（0已发布，1草稿）
    //缩略图
    thumbnail: '',
    status: 0,
    content: ""
})

const articleRule = reactive({ //文章表单规则
    title: [
        { required: true, message: '请输入标题', trigger: 'blur' },
        { min: 1, max: 30, message: '长度在 1 到 30 个字符', trigger: 'blur' }
    ],
    summary: [
        { required: true, message: '请输入文章摘要', trigger: 'blur' },
        { min: 6, max: 300, message: '长度在 6 到 300 个字符', trigger: 'blur' }
    ]
})
let articleRef = ref()

let fileList = ref([])

//发布文章
function writeArticle() {
    articleRef.value.validate(async (valid) => {
        if (valid) {
            if (article.value.id === undefined) {
                article.value.status = 0
                article.value.content = tinymce.activeEditor?.getContent()
                let res = await _axios.post('/api/article/write', article.value)
                if (res.data.code == 200) {
                    ElMessage({
                        showClose: true,
                        message: res.data.data,
                        type: 'success',
                        appendTo: "#app",
                    })
                    router.push('/backContent')
                } else {
                    ElMessage({
                        showClose: true,
                        message: res.data.message,
                        type: 'error',
                        appendTo: "#app",
                    })
                }
            } else {
                article.value.content = tinymce.activeEditor?.getContent()
                let res = await _axios.put('/api/article/update', article.value)
                if (res.data.code === 200) {
                    ElMessage({
                        showClose: true,
                        message: res.data.data,
                        type: 'success',
                        appendTo: "#app",
                    })
                    router.push('/backContent')
                } else {
                    ElMessage({
                        showClose: true,
                        message: res.data.message,
                        type: 'error',
                        appendTo: "#app",
                    })
                }
            }
        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'warning',
                appendTo: "#app",
            })
        }
    })
}

//保存到草稿箱
function saveArticle() {
    articleRef.value.validate(async (valid) => {
        if (valid) {
            article.value.status = 1
            article.value.content = tinymce.activeEditor?.getContent()
            let res = await _axios.post('/api/article/write', article.value)
            if (res.data.code == 200) {
                ElMessage({
                    showClose: true,
                    message: res.data.data,
                    type: 'success',
                    appendTo: "#app",
                })
            } else {
                ElMessage({
                    showClose: true,
                    message: res.data.message,
                    type: 'error',
                    appendTo: "#app",
                })
            }
        } else {
            ElMessage({
                showClose: true,
                message: "请按规则填写",
                type: 'warning',
                appendTo: "#app",
            })
        }
    })
}

function onExceed() {
    ElMessage({
        showClose: true,
        message: "只能上传一个文件",
        type: 'warning',
        appendTo: "#app",
    })
}

let uploadLimit = ref(1)
async function uploadFile(img) {
    let res = await _axios.post('/api/upload',
        {
            img: img.file
        },
        {
            headers: { 'Content-Type': 'multipart/form-data' },
        })
    if (res.data.code == 200) {
        article.value.thumbnail = "http://47.92.174.180:8080"+res.data.data
        ElMessage({
            showClose: true,
            message: "缩略图上传成功",
            type: 'success',
            appendTo: "#app",
        })
    } else {
        ElMessage({
            showClose: true,
            message: res.data.message,
            type: 'error',
            appendTo: "#app",
        })
    }
}
</script>

<template>
    <div class="backMain">
        <el-form :model="article" :rules="articleRule" ref="articleRef">
            <div style="display: flex;">
                <el-form-item prop="title" label="文章标题">
                    <el-input v-model="article.title" style="width: 570px;height: 40px;" placeholder="请输入文章标题" />
                </el-form-item>
                <el-form-item label="分类">
                    <el-select v-model="article.categoryId" style="width: 200px;" size="large">
                        <el-option v-for="item in allCategory" :key=item.id :label=item.name :value=item.id />
                    </el-select>
                </el-form-item>
                <el-form-item label="标签" style="margin-right: 0;">
                    <el-select v-model="article.tags" multiple style="width: 200px;" size="large">
                        <el-option v-for="item in allTag" :key="item.id" :label="item.name" :value="item.id" />
                    </el-select>
                </el-form-item>
            </div>
            <div style="display: flex;">
                <el-form-item prop="summary" label="文章摘要">
                    <el-input v-model="article.summary" type="textarea" style="width: 570px;" placeholder="请输入文章摘要" />
                </el-form-item>
                <el-form-item label="允许评论" style="align-items: center;">
                    <el-radio-group v-model="article.isComment">
                        <el-radio :value=1>正常</el-radio>
                        <el-radio :value=0>禁止</el-radio>
                    </el-radio-group>
                </el-form-item>
                <el-form-item label="是否置顶" style="align-items: center;margin-right: 0;">
                    <el-radio-group v-model="article.isTop">
                        <el-radio :value=1>是</el-radio>
                        <el-radio :value=0>否</el-radio>
                    </el-radio-group>
                </el-form-item>
            </div>
            <div style="display: flex;">
                <el-form-item label="缩略图" style="margin-right: 450px;">
                    <el-upload class="upload-demo" drag name="img" list-type="picture" :limit=uploadLimit
                        :file-list="fileList" accept=".jpg,.png" :http-request="uploadFile" :on-exceed="onExceed"
                        style="width: 400px;">
                        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
                        <div class="el-upload__text">
                            将文件拖到此处，或 <em>点击上传</em>
                        </div>
                        <template #tip>
                            <div class="el-upload__tip">
                                只能上传jpg/png文件, 且不超过10MB
                            </div>
                        </template>
                    </el-upload>
                </el-form-item>
                <div v-if="article.id === undefined">
                    <el-button type="primary" size="large" style="margin-bottom: 25px;"
                        @click="writeArticle">发布</el-button><br>
                    <el-button type="info" size="large" @click="saveArticle">保存到草稿箱</el-button>
                </div>
                <div v-else>
                    <el-button type="primary" size="large" style="margin-bottom: 25px;"
                        @click="writeArticle">更新</el-button>
                </div>
            </div>
            <div id="tinymce">
            </div>
        </el-form>
    </div>
</template>

<style scoped>
.el-form .el-form-item {
    font-weight: 600;
    margin-right: 60px;
}
</style>